package com.github.live.receiver;

import android.content.Context;
import android.content.Intent;

import com.github.livebase.event.Event;
import com.github.livebase.event.EventBus;
import com.github.livebase.event.SimpleEventBus;

import java.util.Calendar;
import java.util.Date;

public class ClockReceiver extends CloseableReceiver  {
    public static String action = Intent.ACTION_TIME_TICK;
    private long time;
    public ClockReceiver() {
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!action.equals(intent.getAction())) {
            return;
        }
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        EventBus bus = SimpleEventBus.getDefault();
        // 分发时间改变事件
        bus.publish( new Event(EventBus.EVENT_CHANGE_TIME, date));
        if (date.getTime() - time > 24*3600_000) {
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            time = calendar.getTimeInMillis();
            // 分发日期改变事件
            bus.publish(new Event(EventBus.EVENT_CHANGE_DATE, calendar.getTime()));
        }
    }

    @Override
    public void close() {

    }
}